<template>
  <div class="upload-container">
    <span title="我的图库" class="gallery-trigger" @click="dialogVisible=true">
      <i class="el-icon-picture-outline" />
    </span>

    <el-drawer
      title="我的图库"
      :visible.sync="dialogVisible"
      width="80%"
      :wrapper-closable="false"
      class="mt-dialog"
      direction="ttb"
      size="100%"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-container class="gallery-container">
        <el-main>
          <el-row :gutter="20">
            <!-- 左侧上传区域 -->
            <el-col :span="12" class="upload-section">
              <div class="section-card">
                <h3 class="section-title">上传图片</h3>
                <uploadimage />
              </div>
            </el-col>

            <!-- 右侧图片展示区域 -->
            <el-col :span="12" class="gallery-section">
              <el-tabs type="border-card">
                <!-- 热点图片标签页 -->
                <el-tab-pane v-loading="hotLoading">
                  <span slot="label" class="tab-label">
                    <svg-icon icon-class="top" />
                    热点图片
                  </span>
                  <div class="action-bar">
                    <el-button
                      type="primary"
                      size="small"
                      :disabled="!selectedImages.length"
                      @click="handleImageInsert"
                    >
                      插入选中图片
                    </el-button>
                  </div>
                  <div class="gallery-content">
                    <vue-select-image
                      :data-images="hotImages"
                      w="200"
                      h="200"
                      @onselectimage="onSelectImage"
                    />

                  </div>
                </el-tab-pane>

                <!-- 全部图片标签页 -->
                <el-tab-pane v-loading="allLoading" label="全部图片">
                  <div class="filter-section">
                    <!-- 目录和添加人筛选 -->
                    <div class="filter-group">
                      <el-cascader
                        v-model="selected_directory"
                        v-loading="treeLoading"
                        :options="directories"
                        :props="{ children: 'children', label: 'name', value: 'id' }"
                        placeholder="选择目录"
                        clearable
                        size="small"
                        class="filter-item"
                        :show-all-levels="false"
                        change-on-select
                        @change="getList"
                      />

                      <el-select
                        v-model="owner_id"
                        v-loading="ownersLoading"
                        placeholder="选择添加人"
                        filterable
                        size="small"
                        clearable
                        class="filter-item"
                      >
                        <el-option
                          v-for="user in users"
                          :key="user.id"
                          :label="user.username"
                          :value="user.id"
                        />
                      </el-select>
                    </div>

                    <!-- 搜索框 -->
                    <div class="search-box">
                      <el-input
                        v-model="kw"
                        placeholder="搜索图片..."
                        clearable
                        size="small"
                        @keyup.native.enter="getList"
                      >
                        <el-button slot="append" icon="el-icon-search" @click="getList" />
                      </el-input>
                    </div>
                    <div class="action-bar">
                      <el-button
                        type="primary"
                        size="small"
                        :disabled="!selectedImages.length"
                        @click="handleImageInsert"
                      >
                        插入选中图片
                      </el-button>
                    </div>
                  </div>

                  <div class="gallery-content">
                    <vue-select-image
                      :data-images="allImages"
                      w="200"
                      h="200"
                      @onselectimage="onSelectImage"
                    />

                    <!-- 分页 -->
                    <el-pagination
                      v-if="allImages.length"
                      background
                      :current-page="page"
                      :page-sizes="[20,40,80,100]"
                      :page-size="pagesize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total"
                      class="pagination"
                      @size-change="handleSizeChange"
                      @current-change="handlePageChange"
                    />
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </el-drawer>
  </div>
</template>

<script>
import Uploadimage from '../uploadimage'
require('vue-select-image/dist/vue-select-image.css')
import VueSelectImage from 'vue-select-image'
import EditorImage from '../editorImage'
import { GetTree } from '@/api/cms/directory'
import { Get as GetImages } from '@/api/cms/image'
import { Get as GetUsers } from '@/api/users'

const qs = require('qs')

export default {
  name: 'Gallery',
  components: { Uploadimage, VueSelectImage, EditorImage },

  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },

  data() {
    return {
      link: '',
      dialogVisible: false,
      selectedImages: [],
      hotImages: [],
      allImages: [],
      users: [],
      owner_id: null,
      ownersLoading: false,
      treeLoading: false,
      directories: [],
      selected_directory: [],
      kw: null,
      order_by: '',
      order_desc: '',
      pagesize: 20,
      page: 1,
      total: 0,
      allLoading: false,
      hotLoading: false
    }
  },

  created() {
    this.getHot()
    this.getList()
    this.handleFetchTree()
    this.handleFetchGetUsers()
  },

  methods: {
    getList() {
      this.allLoading = true
      GetImages(null, qs.stringify({
        kw: this.kw,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        directory_id: this.selected_directory && this.selected_directory[0],
        owner_id: this.owner_id
      }))
        .then(response => {
          this.allImages = response.data.data.map(m => ({
            ...m,
            src: m.url
          }))
          this.total = response.data.total
        })
        .catch(e => console.error(e))
        .finally(() => {
          this.allLoading = false
        })
    },

    getHot() {
      this.hotLoading = true
      GetImages(null, 'hot=1')
        .then(response => {
          this.hotImages = response.data.map(m => ({
            ...m,
            src: m.url
          }))
        })
        .catch(e => console.error(e))
        .finally(() => {
          this.hotLoading = false
        })
    },

    handleClickGoogle(v) {
      if (v) window.open(`https://www.google.com/searchbyimage?image_url=${v}`)
    },

    handleFetchTree() {
      this.treeLoading = true
      GetTree()
        .then(response => {
          this.directories = response.data
        })
        .catch(e => console.error(e))
        .finally(() => {
          this.treeLoading = false
        })
    },

    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers()
        .then(response => {
          this.users = response.data.data
        })
        .catch(e => console.error(e))
        .finally(() => {
          this.ownersLoading = false
        })
    },

    handleInsertBytUrl(url) {
      const arr = [{ url, width: 800, height: 'auto' }]
      this.$emit('successCBK', arr)
    },

    handleImageInsert() {
      if (this.selectedImages.length > 0) {
        this.handleInsertBytUrl(this.selectedImages[0].url)
        this.dialogVisible = false
      }
    },

    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },

    handlePageChange(val) {
      this.page = val
      this.getList()
    },

    onSelectImage(v) {
      this.selectedImages = [v]
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  .gallery-trigger {
    cursor: pointer;
    i {
      font-size: 20px;
      transition: color 0.3s;
      &:hover {
        color: #409EFF;
      }
    }
  }
}

.gallery-container {
  padding: 20px;

  .section-card {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .section-title {
      margin: 0 0 20px;
      font-size: 16px;
      color: #303133;
    }
  }
}

.filter-section {
  margin-bottom: 20px;

  .filter-group {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;

    .filter-item {
      min-width: 180px;
    }
  }

  .search-box {
    width: 100%;
    max-width: 400px;
  }
}

.gallery-content {
  .action-bar {
    margin: 16px 0;
    text-align: center;
  }
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 5px;
}

// Deep selectors for element-ui overrides
::v-deep {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
  }

  .el-tabs--border-card {
    box-shadow: none;
  }

  .el-tab-pane {
    padding: 20px;
  }
}
</style>
